#include "authworker.h"
#include "databasehandler.h"
#include <QSqlQuery>
#include <QVariant>
#include <QDebug>
#include <QThread>
#include <QDateTime>

AuthWorker::AuthWorker(DatabaseHandler *dbHandler, const QString &username, const QString &password, QObject *parent)
    : QObject(parent), m_dbHandler(dbHandler), m_username(username), m_password(password) 
{
    qDebug() << "AuthWorker created in thread:" << QThread::currentThreadId();
}

void AuthWorker::processAuth()
{
    // 用户认证处理流程
    qDebug() << "[AuthWorker] 开始处理用户认证，线程ID:" << QThread::currentThreadId();
    qDebug() << "[AuthWorker] 数据库连接状态:" << m_dbHandler->database().isOpen() 
              << "连接名称:" << m_dbHandler->database().connectionName();
    
    qint64 startTime = QDateTime::currentMSecsSinceEpoch();

    // 准备SQL查询
    qDebug() << "[AuthWorker] 准备用户认证查询，用户名:" << m_username;
    QSqlQuery query(m_dbHandler->database());
    query.prepare("SELECT password_hash, role, full_name FROM users WHERE username = :username");
    query.bindValue(":username", QVariant(m_username));

    // 执行查询
    qDebug() << "[AuthWorker] 正在执行用户认证查询";
    bool querySuccess = query.exec();
    qDebug() << "[AuthWorker] 查询执行时间:" << (QDateTime::currentMSecsSinceEpoch() - startTime) << "ms";
    
    bool authSuccess = false;
    QString fullName;
    QString role;

    // 处理查询结果
    if (querySuccess && query.next()) {
        qDebug() << "[AuthWorker] 找到用户记录，开始验证密码";
        
        // 密码哈希验证
        qint64 hashTimeStart = QDateTime::currentMSecsSinceEpoch();
        QString storedHash = query.value("password_hash").toString();
        QString computedHash = m_dbHandler->hashPassword(m_password);
        
        qDebug() << "[AuthWorker] 密码哈希计算时间:" << (QDateTime::currentMSecsSinceEpoch() - hashTimeStart) << "ms";
        authSuccess = (storedHash == computedHash);
        
        if (authSuccess) {
            qDebug() << "[AuthWorker] 密码验证成功";
            fullName = query.value("full_name").toString();
            role = query.value("role").toString();
        } else {
            qDebug() << "[AuthWorker] 密码验证失败";
        }
    } else {
        qDebug() << "[AuthWorker] 用户不存在或查询失败";
    }

    qDebug() << "[AuthWorker] 认证处理完成，总耗时:" << (QDateTime::currentMSecsSinceEpoch() - startTime) << "ms";
    emit authResult(authSuccess, fullName, role);
    emit authComplete(authSuccess);
}